package com.jijuxie.common.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.jijuxie.common.cache.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CaptchaUtils {
    
    @Autowired
    @Qualifier("localCacheServiceImpl")  // 优先使用本地缓存
    private CacheService cacheService;

    private static final long CAPTCHA_TIMEOUT = 300; // 5分钟过期
    private static final String CAPTCHA_PREFIX = "captcha:";
    
    /**
     * 生成验证码
     */
    public Map<String, Object> createCaptcha() {
        // 生成验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40);
        // 生成uuid
        String uuid = IdUtil.simpleUUID();
        // 保存验证码
        cacheService.set(CAPTCHA_PREFIX + uuid, captcha.getCode(), CAPTCHA_TIMEOUT);

        // 返回验证码信息
        Map<String, Object> result = new HashMap<>();
        result.put("uuid", uuid);
        result.put("img", captcha.getImageBase64());

        return result;
    }
    
    /**
     * 验证验证码
     */
    public boolean verifyCaptcha(String uuid, String code) {
        if (code == null || code.isEmpty()) {
            return false;
        }
        String key = CAPTCHA_PREFIX + uuid;
        String storedCode = cacheService.get(key);
        if (storedCode == null) {
            return false;
        }
        // 验证成功后删除验证码
        if (code.equalsIgnoreCase(storedCode)) {
            cacheService.delete(key);
            return true;
        }
        return false;
    }
}
